﻿using LaserAutoTest.Worker.Jobs;
using Quartz;
using System.Configuration;
using System.Data;
using System.Reflection;

namespace LaserAutoTest.Worker
{
    public static class RegisterJob
    {
        public static async Task RegisterJobs(this IScheduler scheduler)
        {
            if (ConfigurationManager.AppSettings["IsJobStart"] == "true")
                await RegisterAllJob(scheduler);
        }

        private static async Task RegisterTestJob(IScheduler scheduler)
        {
            IJobDetail job = JobBuilder.Create<HCJob>()
                .WithIdentity("HCJob")
                .Build();

            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("HCJobTrigger")
                .StartNow()
                .WithCronSchedule("0/1 * * * * ?")
                .Build();
            await scheduler.ScheduleJob(job, trigger);
        }

        private static async Task RegisterAllJob(IScheduler scheduler)
        {
            // 获取当前执行程序集中的所有类型  
            var types = Assembly.GetExecutingAssembly().GetTypes();

            // 查找所有实现了IJob接口的类型  
            var jobTypes = types.Where(t => typeof(IJob).IsAssignableFrom(t) && !t.IsAbstract);

            foreach (var jobType in jobTypes)
            {
                // 创建作业详情  
                IJobDetail job = JobBuilder.Create(jobType)
                    .WithIdentity(jobType.Name)
                    .Build();

                // 创建触发器，这里使用简单的触发器，你也可以根据需要使用 Cron 触发器或其他类型的触发器  
                ITrigger trigger = TriggerBuilder.Create()
                    .WithIdentity(jobType.Name + "Trigger")
                    .StartNow()
                     .WithCronSchedule(ConfigurationManager.AppSettings[$"{jobType.Name}Cron"])//"0/1 * * * * ?"
                    .Build();

                // 将作业和触发器加入到调度器中  
                await scheduler.ScheduleJob(job, trigger);
            }
        }
    }
}
